package cn.mujiankeji.mbrowser.app.应用组件

import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.size
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.ColorFilter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.res.vectorResource
import androidx.compose.ui.unit.dp
import cn.mujiankeji.mbrowser.app.应用文件
import cn.mujiankeji.mbrowser.工具.mlog
import cn.mujiankeji.mbrowser.界面.图标.MyIconPack
import cn.mujiankeji.mbrowser.界面.图标.myiconpack.图片
import coil3.ImageLoader
import coil3.compose.AsyncImage
import coil3.compose.LocalPlatformContext
import com.blankj.utilcode.util.FileUtils
import 操作.工具类.right


@Composable
fun 应用图片(地址 : String,modifier: Modifier,默认图标 : ImageVector = MyIconPack.图片){
    // 文字图标  t:名称#FF223366
    if (地址.startsWith("t:")){
        // 这里可以自定义文字图标的实现
    }
    else if (地址.startsWith("http") || 地址.startsWith("file:")){
        var error by remember { mutableStateOf(false) }
        Box(modifier){
            AsyncImage(
                model = 地址,
                modifier = modifier,
                contentScale = ContentScale.Crop,
                contentDescription = "",
                imageLoader = ImageLoader
                    .Builder(LocalPlatformContext.current)
                    .build(),
                onError = {
                    mlog(it.result.throwable.message)
                    it.result.throwable.printStackTrace()
                    error =true
                }
            )
            mlog("ddd",error,地址)
            if (error){
                Image(
                    imageVector = 默认图标,
                    contentDescription = "",
                    modifier = modifier
                )
            }
        }
    }

    else {

        // 内置图标
        取内置图标(地址.right(":")?:地址)?.let {
            Image(
                imageVector = it,
                contentDescription = "",
                modifier = modifier
            )
            return
        }

        // 本地图标
        val localImg = 应用文件.图片库路径() + 地址
        if (FileUtils.isFileExists(localImg)){
           应用图片("file://$localImg",modifier,默认图标)
        }
        else{
            // 其他情况显示默认图标
            Image(
                imageVector = 默认图标,
                contentDescription = "",
                modifier = modifier
            )
        }




    }
}

private fun 取内置图标(name : String) : ImageVector?{
    return try {
        val field = MyIconPack::class.java.getDeclaredField(name)
        field.get(null) as? ImageVector
    } catch (e: Exception) {
        null
    }
}